package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.*;
import com.example.HaiDLaobackend.service.*;
import com.example.HaiDLaobackend.service.CouponService;
import com.example.HaiDLaobackend.service.UserCouponService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final CartItemService cartItemService;
    private final ProductService productService;
    private final RefundRequestService refundRequestService;
    private final ProductReviewService productReviewService;
    private final CouponService couponService;
    private final UserCouponService userCouponService;

    public OrderController(OrderService orderService, OrderItemService orderItemService, CartItemService cartItemService, ProductService productService, RefundRequestService refundRequestService, ProductReviewService productReviewService, CouponService couponService, UserCouponService userCouponService) {
        this.orderService = orderService;
        this.orderItemService = orderItemService;
        this.cartItemService = cartItemService;
        this.productService = productService;
        this.refundRequestService = refundRequestService;
        this.productReviewService = productReviewService;
        this.couponService = couponService;
        this.userCouponService = userCouponService;
    }

    @PostMapping("/checkout")
    @Transactional
    public ApiResponse<Map<String, Object>> checkout(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId){
        if (currentUserId == null) return ApiResponse.error("未登录");
        List<CartItemEntity> cartItems = cartItemService.list(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId));
        if (cartItems.isEmpty()) {
            return ApiResponse.error("购物车为空");
        }
        BigDecimal total = BigDecimal.ZERO;
        List<OrderItemEntity> orderItems = new ArrayList<>();
        for (CartItemEntity ci : cartItems) {
            ProductEntity p = productService.getById(ci.getProductId());
            if (p == null || p.getStatus() == null || p.getStatus() == 0) {
                return ApiResponse.error("包含已下架商品");
            }
            BigDecimal line = p.getPrice().multiply(BigDecimal.valueOf(ci.getQuantity()));
            total = total.add(line);
            OrderItemEntity oi = new OrderItemEntity();
            oi.setProductId(p.getId());
            oi.setTitle(p.getTitle());
            oi.setCoverImage(p.getCoverImage());
            oi.setPrice(p.getPrice());
            oi.setQuantity(ci.getQuantity());
            orderItems.add(oi);
        }
        OrderEntity order = new OrderEntity();
        order.setUserId(currentUserId);
        order.setMerchantName("海D捞旗舰店");
        order.setTotalAmount(total);
        order.setStatus("CREATED");
        orderService.save(order);
        Long orderId = order.getId();
        for (OrderItemEntity oi : orderItems) {
            oi.setOrderId(orderId);
        }
        orderItemService.saveBatch(orderItems);
        cartItemService.remove(new LambdaQueryWrapper<CartItemEntity>().eq(CartItemEntity::getUserId, currentUserId));

        Map<String, Object> data = new HashMap<>();
        data.put("order", order);
        data.put("items", orderItems);
        return ApiResponse.ok(data);
    }

    public static class CheckoutSelectedBody {
        private List<Long> productIds;
        private Long couponId;
        private Long userCouponId;
        
        public List<Long> getProductIds() { return productIds; }
        public void setProductIds(List<Long> productIds) { this.productIds = productIds; }
        public Long getCouponId() { return couponId; }
        public void setCouponId(Long couponId) { this.couponId = couponId; }
        public Long getUserCouponId() { return userCouponId; }
        public void setUserCouponId(Long userCouponId) { this.userCouponId = userCouponId; }
    }

    @PostMapping("/checkoutSelected")
    @Transactional
    public ApiResponse<Map<String, Object>> checkoutSelected(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                                             @RequestBody CheckoutSelectedBody body){
        if (currentUserId == null) return ApiResponse.error("未登录");
        if (body == null || body.getProductIds() == null || body.getProductIds().isEmpty()) {
            return ApiResponse.error("未选择商品");
        }
        List<CartItemEntity> cartItems = cartItemService.list(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId)
            .in(CartItemEntity::getProductId, body.getProductIds()));
        if (cartItems.isEmpty()) {
            return ApiResponse.error("购物车为空或无可结算商品");
        }
        BigDecimal originalAmount = BigDecimal.ZERO;
        List<OrderItemEntity> orderItems = new ArrayList<>();
        for (CartItemEntity ci : cartItems) {
            ProductEntity p = productService.getById(ci.getProductId());
            if (p == null || p.getStatus() == null || p.getStatus() == 0) {
                return ApiResponse.error("包含已下架商品");
            }
            BigDecimal line = p.getPrice().multiply(BigDecimal.valueOf(ci.getQuantity()));
            originalAmount = originalAmount.add(line);
            OrderItemEntity oi = new OrderItemEntity();
            oi.setProductId(p.getId());
            oi.setTitle(p.getTitle());
            oi.setCoverImage(p.getCoverImage());
            oi.setPrice(p.getPrice());
            oi.setQuantity(ci.getQuantity());
            orderItems.add(oi);
        }
        
        // 处理优惠券
        BigDecimal discountAmount = BigDecimal.ZERO;
        Long couponId = null;
        UserCouponEntity userCoupon = null;
        
        if (body.getUserCouponId() != null) {
            // 验证优惠券
            userCoupon = userCouponService.getById(body.getUserCouponId());
            if (userCoupon == null || !userCoupon.getUserId().equals(currentUserId) || userCoupon.getStatus() != 0) {
                return ApiResponse.error("优惠券不可用");
            }
            
            CouponEntity coupon = couponService.getById(userCoupon.getCouponId());
            if (coupon == null || coupon.getStatus() == null || coupon.getStatus() == 0) {
                return ApiResponse.error("优惠券不存在或已失效");
            }
            
            // 检查有效期
            java.time.LocalDateTime now = java.time.LocalDateTime.now();
            if (coupon.getStartTime() != null && now.isBefore(coupon.getStartTime())) {
                return ApiResponse.error("优惠券尚未生效");
            }
            if (coupon.getEndTime() != null && now.isAfter(coupon.getEndTime())) {
                return ApiResponse.error("优惠券已过期");
            }
            
            // 检查使用门槛
            if (coupon.getThresholdAmount() != null && originalAmount.compareTo(coupon.getThresholdAmount()) < 0) {
                return ApiResponse.error("订单金额未达到优惠券使用门槛");
            }
            
            discountAmount = coupon.getDiscountAmount();
            couponId = coupon.getId();
        }
        
        // 计算最终金额（不能小于0）
        BigDecimal finalAmount = originalAmount.subtract(discountAmount);
        if (finalAmount.compareTo(BigDecimal.ZERO) < 0) {
            finalAmount = BigDecimal.ZERO;
        }
        
        // 创建订单
        OrderEntity order = new OrderEntity();
        order.setUserId(currentUserId);
        order.setMerchantName("海D捞旗舰店");
        order.setOriginalAmount(originalAmount);
        order.setDiscountAmount(discountAmount);
        order.setTotalAmount(finalAmount);
        order.setCouponId(couponId);
        order.setStatus("CREATED");
        orderService.save(order);
        Long orderId = order.getId();
        
        // 保存订单项
        for (OrderItemEntity oi : orderItems) {
            oi.setOrderId(orderId);
        }
        orderItemService.saveBatch(orderItems);
        
        // 使用优惠券（标记为已使用）
        if (userCoupon != null) {
            userCoupon.setStatus(1);
            userCoupon.setUsedAt(java.time.LocalDateTime.now());
            userCouponService.updateById(userCoupon);
        }
        
        // 清空购物车
        cartItemService.remove(new LambdaQueryWrapper<CartItemEntity>()
            .eq(CartItemEntity::getUserId, currentUserId)
            .in(CartItemEntity::getProductId, body.getProductIds()));

        Map<String, Object> data = new HashMap<>();
        data.put("order", order);
        data.put("items", orderItems);
        return ApiResponse.ok(data);
    }

    @GetMapping
    public ApiResponse<?> list(
            @RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "20") long pageSize,
            @RequestParam(required = false) String status
    ){
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        LambdaQueryWrapper<OrderEntity> qw = new LambdaQueryWrapper<OrderEntity>()
                .eq(OrderEntity::getUserId, currentUserId)
                .eq(status != null && !status.isEmpty(), OrderEntity::getStatus, status)
                .orderByDesc(OrderEntity::getId);
        Page<OrderEntity> page = orderService.page(new Page<>(pageNum, pageSize), qw);
        List<Map<String,Object>> records = new ArrayList<>();
        for (OrderEntity o : page.getRecords()) {
            List<OrderItemEntity> items = orderItemService.list(new LambdaQueryWrapper<OrderItemEntity>().eq(OrderItemEntity::getOrderId, o.getId()));
            Map<String,Object> m = new HashMap<>();
            m.put("id", o.getId());
            m.put("userId", o.getUserId());
            m.put("merchantName", o.getMerchantName());
            m.put("totalAmount", o.getTotalAmount());
            m.put("originalAmount", o.getOriginalAmount() != null ? o.getOriginalAmount() : o.getTotalAmount());
            m.put("discountAmount", o.getDiscountAmount() != null ? o.getDiscountAmount() : BigDecimal.ZERO);
            m.put("status", o.getStatus());
            m.put("createdAt", o.getCreatedAt());
            List<Map<String,Object>> itemDtos = new ArrayList<>();
            for (OrderItemEntity item : items) {
                Map<String,Object> itemMap = new HashMap<>();
                itemMap.put("id", item.getId());
                itemMap.put("productId", item.getProductId());
                itemMap.put("title", item.getTitle());
                itemMap.put("price", item.getPrice());
                itemMap.put("quantity", item.getQuantity());
                String cover = item.getCoverImage();
                if ((cover == null || cover.isEmpty()) && item.getProductId() != null) {
                    ProductEntity product = productService.getById(item.getProductId());
                    if (product != null) cover = product.getCoverImage();
                }
                itemMap.put("coverImage", cover);
                boolean reviewed = isItemReviewed(currentUserId, o.getId(), item.getId());
                itemMap.put("reviewed", reviewed);
                itemDtos.add(itemMap);
            }
            m.put("items", itemDtos);
            records.add(m);
        }
        Map<String,Object> resp = new HashMap<>();
        resp.put("records", records);
        resp.put("total", page.getTotal());
        resp.put("size", page.getSize());
        resp.put("current", page.getCurrent());
        return ApiResponse.ok(resp);
    }

    @PostMapping("/{orderId}/confirm")
    public ApiResponse<?> confirm(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                  @PathVariable Long orderId){
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        OrderEntity order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(currentUserId)) return ApiResponse.error(404, "订单不存在");
        if (!"SHIPPED".equals(order.getStatus())) return ApiResponse.error(400, "当前状态不可确认收货");
        order.setStatus("COMPLETED");
        orderService.updateById(order);
        return ApiResponse.ok(true);
    }

    @PostMapping("/{orderId}/pay")
    public ApiResponse<Boolean> pay(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                    @PathVariable Long orderId) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        OrderEntity order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(currentUserId)) return ApiResponse.error(404, "订单不存在");
        if (!"CREATED".equals(order.getStatus())) return ApiResponse.error(400, "订单状态不可支付");
        order.setStatus("PAID");
        orderService.updateById(order);
        return ApiResponse.ok(true);
    }

    @DeleteMapping("/{orderId}")
    public ApiResponse<Boolean> delete(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                       @PathVariable Long orderId) {
        if (currentUserId == null) return ApiResponse.error(401, "未登录");
        OrderEntity order = orderService.getById(orderId);
        if (order == null || !order.getUserId().equals(currentUserId)) return ApiResponse.error(404, "订单不存在");
        // 未完成售后不可删除：存在该订单的售后单且状态不为 COMPLETED/REJECTED 则阻止
        long cnt = refundRequestService.count(new LambdaQueryWrapper<RefundRequestEntity>()
                .eq(RefundRequestEntity::getOrderId, orderId)
                .notIn(RefundRequestEntity::getStatus, Arrays.asList("COMPLETED", "REJECTED")));
        if (cnt > 0) {
            return ApiResponse.error(400, "存在未完成售后，无法删除");
        }
        // 先删订单项再删订单
        orderItemService.remove(new LambdaQueryWrapper<OrderItemEntity>()
                .eq(OrderItemEntity::getOrderId, orderId));
        boolean ok = orderService.removeById(orderId);
        return ok ? ApiResponse.ok(true) : ApiResponse.error("删除失败");
    }

    private boolean isItemReviewed(Long userId, Long orderId, Long orderItemId) {
        LambdaQueryWrapper<ProductReviewEntity> wrapper = new LambdaQueryWrapper<ProductReviewEntity>()
                .eq(ProductReviewEntity::getUserId, userId)
                .eq(ProductReviewEntity::getOrderId, orderId);
        if (orderItemId != null) {
            wrapper.eq(ProductReviewEntity::getOrderItemId, orderItemId);
        }
        wrapper.last("LIMIT 1");
        return productReviewService.getOne(wrapper) != null;
    }
}


